<?php
/**
 * Created by PhpStorm.
 * User: stupboy
 * Date: 2018/2/26
 * Time: 16:13
 */

namespace app\adminapi\model;

use app\adminapi\filter;
use app\base\exception\RecordNotFoundException;
use think\Db;
use think\exception\DbException;
use traits\model\SoftDelete;

class Car extends Common
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';

    public function cartype(){
        return $this->hasOne('CarType', 'car_type_id', 'car_type_id');
    }

    /**
     * 查询车辆
     * @param string $type
     * @param string $number
     * @param int $page
     * @param int $num
     * @return mixed
     */
    public function getCar($type='',$number='',$page=1,$num=10 , $company_id = 0 ){
        $where               = [];
        if(!empty($number)){
            $where['number'] = ['like','%'.$number.'%'];
        }
        if(!empty($type)){
            $typeId                     = Db::name('car_type')->where("car_type_name like '%$type%' ")->column('car_type_id');
            $typeStr                    = implode(',',$typeId);
            $where['car.car_type_id'] = empty($typeId) ? -1 : ['in',$typeStr];
        }
        $company_id >0 && $where['company_id|entrust_company_id'] = $company_id;
        $field = 'car_id,number';
        $data['count'] = $this->alias('car')->field($field)->where($where)->whereNull('car.delete_time')->count();
        $condition     = 'car.car_type_id = t.car_type_id';
        $field   .= ',car_type_name,t.car_type_id,company_id,entrust_company_id';
        $cars     = $this->alias('car')
            ->join('car_type t',$condition)
            ->where($where)
            ->page($page,$num)
            ->whereNull('car.delete_time')
            ->field($field)
            ->select();
        $list     = [];
        $driverCar= Db::name('driver_car_use')->alias('a')
            ->join('driver b','a.driver_id = b.driver_id','left')
            ->where('is_default',1)->column('a.car_id,b.name');
        foreach ($cars as $car){
            $car['has_bind'] = isset($driverCar[$car['car_id']]) ? 1 : 0;
            $car['driver']   = $driverCar[$car['car_id']] ?: '-';
            $list[]          = $car;
        }
        $data['list'] = $list;
        return $data;
    }

    /**
     * 新增或者编辑车辆
     * @param $params
     * @return $this|false|int
     * @throws RecordNotFoundException
     * @throws \think\exception\DbException
     */
    public function createOrUpdate($params) {
        $session = (new User())->getLoginUser();
        if(isset($params['car_id'])) {
            $where = ['car_id' => $params['car_id']];
            $buildQuery = function($query) use ($where) {
                self::authCompanyQuery($query, $where, 'a.company_id');
            };

            $car = self::get($buildQuery);
            if(!$car) {
                    throw new RecordNotFoundException();
            }
        }elseif(!self::isSuperAdmin($session) && $session['user']['company_id']) {
            $params['company_id'] = $session['user']['company_id'];
        }

        // 验证单位是否存在
        $this->addRelativeFields( $params, 'app\adminapi\model\Company', $params['company_id'],  [], '关联单位不存在');

        if(isset($params['car_id'])) {
            return $this->isUpdate(true)->save($params);
        }

        $this->data($params)->save();

        return $this;
    }

    /**
     * 车辆列表
     * @param string $fields
     * @param array $where
     * @param int $page
     * @param int $num
     * @return array
     */
    public function carLlist($fields='*',$where=[],$page=1,$num=10){
        $filter          = new filter\CarList();
        $filter->analyzeField();
        list(,$msg)      = $filter->checkField($fields);
        list(,$whereMsg) = $filter->checkWhere($where);
        $data['note'] = "查询条件json输入格式如{'passenger_id':['in','6,7,8,9,10,11,12'],'passenger_name':['like','%王%']}";

        $buildQuery = function($query) use ($whereMsg) {
            self::authCompanyQuery($query, $whereMsg, 'a.company_id');
        };

        try{
            $data['data'] = $this->alias('a')
                ->join('car_type b','a.car_type_id = b.car_type_id','left')
                ->join('company c','a.company_id = c.company_id','left')
                ->join('car_brand d','a.car_brand_id = d.car_brand_id','left')
                ->join('car_brand e','a.car_model_id = e.car_brand_id','left')
                ->join('car_brand f','a.car_series_id = f.car_brand_id','left')
                ->field($msg)
                ->where($buildQuery)
                ->page($page,$num)
                ->order('a.car_id desc')
                ->select();
        }catch (DbException $e){
            abort(0,$e->getMessage());
        }
        $data['count'] = $this->alias('a')
            ->join('car_type b','a.car_type_id = b.car_type_id','left')
            ->join('company c','a.company_id = c.company_id','left')
            ->join('car_brand d','a.car_brand_id = d.car_brand_id','left')
            ->where($buildQuery)
            ->count();
        $data['data']        = $filter->checkData($data['data']);
        $data['description'] = $filter->title;
        $data['fields']      = $filter->fieldTitle;
        return [1,$data];
    }

    /**
     * 车辆购置列表
     * @param string $fields
     * @param array $where
     * @param int $page
     * @param int $num
     * @return array
     */
    public function carbuyLlist($fields='*',$where=[],$page=1,$num=10){
        $filter          = new filter\CarList();
        $filter->analyzeField();
        list(,$msg)      = $filter->checkField($fields);
        list(,$whereMsg) = $filter->checkWhere($where);
        $data['note'] = "查询条件json输入格式如{'passenger_id':['in','6,7,8,9,10,11,12'],'passenger_name':['like','%王%']}";
        try{
            $data['data'] = $this->name('audit')
                ->field($msg)
                ->where($whereMsg)
                ->page($page,$num)
                ->select();
        }catch (DbException $e){
            abort(0,$e->getMessage());
        }
        $data['count'] = $this->alias('a')
            ->join('car_type b','a.car_type_id = b.car_type_id','left')
            ->join('company c','a.company_id = c.company_id','left')
            ->join('car_brand d','a.car_brand_id = d.car_brand_id','left')
            ->where($whereMsg)
            ->whereNull('a.delete_time')
            ->count();
        $data['data']        = $filter->checkData($data['data']);
        $data['description'] = $filter->title;
        $data['fields']      = $filter->fieldTitle;
        return [1,$data];
    }
}